package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.mapper.ClassroomMapper;
import cn.tedu.knows.portal.mapper.QuestionMapper;
import cn.tedu.knows.portal.mapper.UserRoleMapper;
import cn.tedu.knows.portal.model.Classroom;
import cn.tedu.knows.portal.model.User;
import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.model.UserRole;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.RegisterVo;
import cn.tedu.knows.portal.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClassroomMapper classroomMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private QuestionMapper questionMapper;
    private List<User> users =new CopyOnWriteArrayList<>();
    private Map<String,User> teacherMap=new ConcurrentHashMap<>();

    @Override
    public void registerStudent(RegisterVo registerVo) {
        QueryWrapper<Classroom> query =new QueryWrapper<>();
        query.eq("invite_code",registerVo.getInviteCode());
        Classroom classroom=classroomMapper.selectOne(query);
        if (classroom==null){
            throw new ServiceException("邀请码错误！");
        }
        User user =userMapper.findUserByUsername(registerVo.getPhone());
        if (user!=null){
            throw new ServiceException("手机号已经被注册！");
        }
        PasswordEncoder encoder=new BCryptPasswordEncoder();
        String pwd="{bcrypt}"+encoder.encode(registerVo.getPassword());
        User u =new User()
                .setUsername(registerVo.getPhone())
                .setNickname(registerVo.getNickname())
                .setPassword(pwd)
                .setClassroomId(classroom.getId())
                .setCreatetime(LocalDateTime.now())
                .setEnabled(1)
                .setLocked(0)
                .setType(0);
        int num =userMapper.insert(u);
        if (num!=1){
            throw new ServiceException("数据库忙！");
        }
        UserRole userRole =new UserRole()
                .setUserId(u.getId())
                .setRoleId(2);
        num =userRoleMapper.insert(userRole);
        if (num!=1){
            throw new ServiceException("数据库忙！");
        }
    }

    @Override
    public List<User> getTeachers() {
        if (users.isEmpty()){
            synchronized (users){
                if (users.isEmpty()){
                    List<User> users =userMapper.findTeachers();
                    this.users.addAll(users);
                    for (User u :users) {
                        teacherMap.put(u.getNickname(),u);
                    }
                }
            }
        }
        return users;
    }

    @Override
    public Map<String, User> getTeacherMap() {
        if (teacherMap.isEmpty()){
            getTeachers();
        }
        return teacherMap;
    }

    @Override
    public UserVo getUserVo(String username) {
        User user=userMapper.findUserByUsername(username);
        int count =questionMapper.countQuestionsByUserId(user.getId());
        UserVo userVo =new UserVo()
                .setId(user.getId())
                .setUsername(user.getUsername())
                .setNickname(user.getNickname())
                .setQuestions(count);
        return userVo;
    }
}
